package hydrap2p.modulemanager;

import java.util.Arrays;
import java.util.List;

import org.apache.thrift.TException;

import hydrap2p.modulemanager.ModuleInfo;
import hydrap2p.modulemanager.ModuleListener;
import hydrap2p.modulemanager.ModuleManager;
import hydrap2p.modulemanager.listen.Listeners;

public class ProxyModuleListener implements ModuleListener.Iface {
/**
 * Watch a ModuleManager on the other side of a ProxyManager and tell the real ModuleManager about it
 */
	
	private final ModuleController controller;
	private final ModuleManager.Iface manager;
	
	public ProxyModuleListener(ModuleController controller, ModuleManager.Iface manager)
	{
		this.controller=controller;
		this.manager=manager;
	}
	
	@Override
	public void addModule(ModuleInfo module) {
		module.server="remote";
		ModuleStatusRemote status=new ModuleStatusRemote(manager, module);
		ModuleStatus oldstatus = controller.getStatus(module.name, module.server);
		if (oldstatus!=null && oldstatus instanceof ModuleStatusRemote)
		{
			((ModuleStatusRemote)oldstatus).updateInfo(module);
			Listeners.updateModule(module);
		}
		else
		{
			controller.addModule(module.name, module.server, status);
			Listeners.addModule(module);
		}
	}

	@Override
	public void updateModule(ModuleInfo module) {
		module.server="remote";
		ModuleStatus status=controller.getStatus(module.name, module.server);
		if (status instanceof ModuleStatusRemote)
			((ModuleStatusRemote)status).updateInfo(module);
		Listeners.updateModule(module);
	}

	@Override
	public void delModule(ModuleInfo module) {
		module.server="remote";
		Listeners.delModule(module);
	}

	@Override
	public void ping() throws TException {
		
	}

	@Override
	public List<String> supportedInterfaces() throws TException {
		return Arrays.asList("Service", "ModuleListener");
	}

}
